<?php

class Cache
{
    private $Memcache;
    private $MemcacheFlag;
    public function __construct() {
        if (config::memcache_enable) {
            $this->MemcacheFlag = true;
            $this->Memcache = new Memcache;
            $result = $this->Memcache->connect(config::memcache_host, config::memcache_port);
            if (!$result) {
                $this->MemcacheFlag = false;
            }
        } else {
            $this->MemcacheFlag = false;
        }
    }
    
    public  function setCache($key, $value, $flag = '0', $time = '0') {
        if ($this->MemcacheFlag) {
            return $this->Memcache->set($key, $value, $flag, $time); 
        } else {
            return Setting::setVar($key, $value, $flag, $time);
        }
    }
    
    public  function getCache($key) {
        if ($this->MemcacheFlag) {
            $value = $this->Memcache->get($key); 
        } else {
            $value = Setting::getVar($key);
        }
        return $value;
    }

    public  function replaceCache($key, $value, $flag = '0', $time = '0') {
        if ($this->MemcacheFlag) {
            return $this->Memcache->replace($key, $value, $flag, $time); 
        } else {
            return Setting::setVar($key, $value, $flag, $time);
        }
    }
    
    public  function deleteCache($key) {
        if ($this->MemcacheFlag) {
            return $this->Memcache->delete($key); 
        } else {
            return Setting::deleteVar($key);
        }
    }

    public  function flushCache($key) {
        if ($MemcacheFlag) {
            return $this->Memcache->flush();
        } 
    }
    
    public function lock($key) {
        while (1) {
                $lockflag = $this->getCache($key);
                if ($lockflag) {
                    usleep(200);
                } else {
                    $this->setCache($key, true, 0, 5);
                    return true;
                }
            }
    }
    
    public function unlock($key) {
        return $this->deleteCache($key);
    }
}




